package com.shanzmoo.stm.admin.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.shanzmoo.db.stm.entity.StmSysMenuEntity;
import com.shanzmoo.db.stm.entity.StmSysRoleEntity;
import com.shanzmoo.db.stm.service.IStmMemberRoleService;
import com.shanzmoo.db.stm.service.IStmSysMenuService;
import com.shanzmoo.db.store.entity.StoreMemberEntity;
import com.shanzmoo.db.sys.entity.MenuEntity;
import com.shanzmoo.db.sys.entity.RoleEntity;
import com.shanzmoo.db.sys.entity.UserEntity;
import com.shanzmoo.db.sys.service.IMenuService;
import com.shanzmoo.db.sys.service.IUserRoleService;
import com.shanzmoo.stm.admin.domain.bo.AuthStoreMemberBO;
import com.shanzmoo.stm.admin.manager.SysUserManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义 UserDetailsService
 *
 * @author: Gzhao 2020/11/9
 */
@Slf4j
@Service
public class AuthUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserManager sysUserManager;
    @Autowired
    private IStmMemberRoleService memberRoleService;
    @Autowired
    private IStmSysMenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("用户名:" + username);

        StoreMemberEntity userEntity = sysUserManager.getUserByName(username);

        if (ObjectUtil.isNull(userEntity)) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 角色
        List<StmSysRoleEntity> roleList = memberRoleService.getUserRoles(userEntity.getId());

        if (CollUtil.isNotEmpty(roleList)) {
            List<Integer> roleIds = roleList.stream().map(StmSysRoleEntity::getRoleId).collect(Collectors.toList());
            // 权限
            List<StmSysMenuEntity> menuList = menuService.getListByUserId(userEntity.getId());
            if (CollUtil.isNotEmpty(menuList)) {
                List<String> perms = menuList.stream()
                        .filter(e -> StrUtil.isNotBlank(e.getPerms()))
                        .map(StmSysMenuEntity::getPerms)
                        .distinct()
                        .collect(Collectors.toList());
                return AuthStoreMemberBO.create(userEntity, roleIds, perms);
            }
            return AuthStoreMemberBO.create(userEntity, roleIds, null);
        }
        return AuthStoreMemberBO.create(userEntity, null, null);
    }
}
